﻿// 事件.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include "pch.h"
#include <iostream>
#include <Windows.h>

/*
事件：Event
	1. 定义事件  HANDLE
	2. 创建事件  CreateEvent
	3. 等待事件发生 WaitForSingleObject
	4. 取消事件  ResetEvent
	5. 产生事件  SetEvent
*/

#define ISF 1
#define ISFC 0


int n = 0;

HANDLE hEvent;

//很慢
#if ISF
void f()
{
	for (int i = 0; i < 50000000; i++)
	{
		WaitForSingleObject(hEvent, INFINITE);
		n++;
		ResetEvent(hEvent);
	}
}
void f2()
{
	while (1)
	{
		SetEvent(hEvent);	//产生事件
		Sleep(1000);
	}
}

#endif


#if ISFC
void fc1()
{
	while (1)
	{
		WaitForSingleObject(hEvent, INFINITE);
		printf("fc1——————\n");
		Sleep(1000);
		ResetEvent(hEvent);
	}
}
void fc2()
{
	while (1)
	{
		WaitForSingleObject(hEvent, INFINITE);
		printf("fc2======\n");
		Sleep(1000);
		ResetEvent(hEvent);
	}
}
void fc3()
{
	while (1)
	{
		SetEvent(hEvent);	//产生事件
		Sleep(1000);
	}
}
#endif


int main()
{
	hEvent = CreateEvent(NULL,true, false, NULL);



	//创建线程： 
#if ISF
	HANDLE h1 = CreateThread(NULL, NULL,
		(LPTHREAD_START_ROUTINE)f,
		NULL, NULL, NULL);
	HANDLE h2 = CreateThread(NULL, NULL,
		(LPTHREAD_START_ROUTINE)f,
		NULL, NULL, NULL);
	HANDLE h3 = CreateThread(NULL, NULL,
		(LPTHREAD_START_ROUTINE)f2,
		NULL, NULL, NULL);



	WaitForSingleObject(h1, INFINITE);
	WaitForSingleObject(h2, INFINITE);
	WaitForSingleObject(h3, INFINITE);
#endif

#if ISFC
	HANDLE h1 = CreateThread(NULL, NULL,
		(LPTHREAD_START_ROUTINE)fc1,
		NULL, NULL, NULL);

	HANDLE h2 = CreateThread(NULL, NULL,
		(LPTHREAD_START_ROUTINE)fc2,
		NULL, NULL, NULL);

	HANDLE h3 = CreateThread(NULL, NULL,
		(LPTHREAD_START_ROUTINE)fc3,
		NULL, NULL, NULL);


	WaitForSingleObject(h1, INFINITE);
	WaitForSingleObject(h2, INFINITE);
	WaitForSingleObject(h3, INFINITE);
#endif
	printf("n:%d\n", n);        //没有任何方案的话，n最终的值不可能是100000000；



	return 0;
}

